#define _CRT_SECURE_NO_WARNINGS 1
#include <stack>
#include <string>
using namespace std;

class Solution {
public:
    string decodeString(string s) {
        stack<pair<int, string>> stk;
        int num = 0;
        string res = "";

        for (char c : s) {
            if (isdigit(c)) {
                num = num * 10 + (c - '0');
            }
            else if (c == '[') {
                stk.push({ num, res });
                num = 0;
                res = "";
            }
            else if (c == ']') {
                auto [k, prev] = stk.top();
                stk.pop();
                string tmp;
                for (int i = 0; i < k; ++i) {
                    tmp += res;
                }
                res = prev + tmp;
            }
            else {
                res += c;
            }
        }
        return res;
    }
};